import { Controller } from 'egg';
import * as marked from 'marked';
import {readFileSync,writeFileSync,createReadStream,createWriteStream} from 'fs';
import * as mark_pdf from 'markdown-pdf';
import {join} from 'path';
export default class  MarkdownController extends Controller {
    /**
     * 参数：file_name : string  文件名称
     * http://IP:端口号/public/markdown/index.html
     */
    async toHtml(){
        const {ctx}= this;
        const {query}=ctx.request
        try {
            let file_name=query.file_name;
            let basic_path=process.cwd();
            let file_path=join(basic_path,"app/view/",file_name+".md");
            let data=readFileSync(file_path,'utf-8')
            let html_str=marked(data);
            console.log(html_str);
            let target_path=join(basic_path,'app/public/markdown/',"index.html");
            writeFileSync(target_path,html_str);
            return ctx.body=ctx.helper.success_result("操作成功")
        } catch (error) {
            console.log(error);
        }
        ctx.body=ctx.helper.error_result("查询失败")
    }
    /**
     *md转pdf文件
     */
    async toPdf(){
        const {ctx}= this;
        const {query}=ctx.request
        try {
            let file_name=query.file_name;
            let basic_path=process.cwd();
            let file_path=join(basic_path,"app/view/",file_name+".md");
            let target_path=join(basic_path,'app/public/markdown/',"index.pdf");
            createReadStream(file_path).pipe(mark_pdf()).pipe(createWriteStream(target_path))
            return ctx.body=ctx.helper.success_result("操作成功")
        } catch (error) {
            console.log(error);
        }
        ctx.body=ctx.helper.error_result("查询失败")
    }
}